(function(){
var role = require("./role");
var db = require("../../core/db/index");
var config = require("../../core/_include/config");
var AdminCon = require("../../core/admin/_con");
var ResponObj = require("../_include/ResponObj");
module.exports = {
	prefix:"/admin",
	get:{
		"/":function *(){
			try{
				var admin  = role.getAdmin(this);
				this.body = admin;
			}catch(errorMsg){
				this.body = ResponObj("error",errorMsg);
			}
		},
		"/scanUser/:id_or_name":require("./user.rest.js").get["/adminScan/:id_or_name"],
		//管理员退出登录
		"/loginout":function *(){
			try{
				var admin  = role.getAdmin(this);
				//删除loginHash中同管理员名的信息
				db.remove_list(config.dbname.loginHash,{
					admin_id:admin._id
				});
				//清空Cookie
				this.cookies.set("loginSession","");
				this.body = ResponObj("json","管理员下线成功");
			}catch(errorMsg){
				this.body = ResponObj("error",errorMsg);
			}
		}
	},
	post:{
		"/register":function *(next){
			//权限校验
			if(!role.resCheckRole("admin",this)){
				return
			}

			var admin_info = this.request.body;
			//先验证验证码
			admin_info.name = admin_info.name.toLowerCase();
			if(db.find_one(config.dbname.admin,{
				info:{
					name:admin_info.name
				}
			})){
				this.body = ResponObj("error","管理员名已经存在");
			}else if (!RegExp("^([\u4E00-\uFA29]|[\uE7C7-\uE7F3]|[a-zA-Z0-9])*$").test(admin_info.name)) {
				this.body = ResponObj("error","管理员名格式错误");
			}else if(!(admin_info.password&&admin_info.confirm_password)){
				this.body = ResponObj("error","表单不完整");
			}else if(admin_info.password !== admin_info.confirm_password){
				this.body = ResponObj("error","两次密码输入不匹配");
			}else{
				delete admin_info.confirm_password;
				new AdminCon(admin_info);
				this.body = ResponObj("json","管理员注册成功");
			}
			yield next;
		},
		//管理员登录
		//.body:admin_info
		"/login":function *(next){
			var form_data = this.request.body;
			try{
				var admin = AdminCon.login(form_data);
				this.body = ResponObj("json","登陆成功");
				//删除loginHash中同管理员名的信息
				db.remove_list(config.dbname.loginHash,{
					admin_id:admin._id
				});
				//注入新的Session
				var hash = admin._id.substr(2)+(+new Date).toString(16);
				this.cookies.set("loginSession",hash);
				db.insert(config.dbname.loginHash,{
					_id:hash,
					admin_id:admin._id,
					type:"admin",
					beginTime:+new Date
				});
			}catch(errorMsg){
				this.body = ResponObj("error",errorMsg);
			}
			yield next;
		}
	}
}
}());